package ch.il07.converter.presentation.beans;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

import ch.il07.converter.business.MeasurandAction;
import ch.il07.converter.business.ServiceFactoryAdapter;
import ch.il07.converter.business.UnitAction;
import ch.il07.converter.persistence.entities.Measurand;
import ch.il07.converter.presentation.Helper;

public class UnitBean {
	private String currentMeasurand;
	private List<SelectItem> measurandList;
	private String unitName;
	private double unitDivisor;
	private double unitShift;
	private String unitShortcut;

	public UnitBean() {
		measurandList = new ArrayList<SelectItem>();
		MeasurandAction measurandImpl = ServiceFactoryAdapter.getMeasurandActionInstance();

		List<Measurand> privateMeasurands = measurandImpl.getAllPrivateMeasurands(Helper.getUserName());

		List<Measurand> publicMeasurands = measurandImpl.getAllPublicMeasurands();

		for (Measurand measurand : publicMeasurands) {
			measurandList.add(new SelectItem(measurand.getName()));
		}

		for (Measurand measurand : privateMeasurands) {
			measurandList.add(new SelectItem(measurand.getName()));
		}

	}

	public String create() {
		String response = "failure";
		UnitAction ua = ServiceFactoryAdapter.getUnitActionInstance();
		boolean result = ua.addPrivateUnit(currentMeasurand, Helper.getUserName(), unitName, unitDivisor, unitShift, unitShortcut);

		FacesContext fc = Helper.getFacesContext();
		if (result) {
			fc.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Die Einheit wurde gespeichert!", null));
			response = "success";
		} else {
			fc.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Ein Fehler ist beim Speichern der Einheit aufgetretten.", null));
		}

		return response;
	}

	public String cancel() {
		return "cancel";
	}

	public String getCurrentMeasurand() {
		return currentMeasurand;
	}

	public void setCurrentMeasurand(String currentMeasurand) {
		this.currentMeasurand = currentMeasurand;
	}

	public List<SelectItem> getMeasurandList() {
		return measurandList;
	}

	public void setMeasurandList(List<SelectItem> measurandList) {
		this.measurandList = measurandList;
	}

	public String getUnitName() {
		return unitName;
	}

	public void setUnitName(String unitName) {
		this.unitName = unitName;
	}

	public double getUnitDivisor() {
		return unitDivisor;
	}

	public void setUnitDivisor(double unitDivisor) {
		this.unitDivisor = unitDivisor;
	}

	public double getUnitShift() {
		return unitShift;
	}

	public void setUnitShift(double unitShift) {
		this.unitShift = unitShift;
	}

	public String getUnitShortcut() {
		return unitShortcut;
	}

	public void setUnitShortcut(String unitShortcut) {
		this.unitShortcut = unitShortcut;
	}
}